package com.pengiummer.blogpublisher.utils;

import java.io.ByteArrayOutputStream;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class XMLUtils {

	public static Node getNodeByPath(Node ancesterNode, String path,
			boolean createIfNotExist) {
		String nodeNames[] = path.split("/");
		Document document = ancesterNode.getOwnerDocument();
		XPath xPath = XPathFactory.newInstance().newXPath();
		Node nodeStartFrom = ancesterNode;

		for (String nodeName : nodeNames) {
			if(nodeName.equals(""))
				continue;
			Node node;
			try {
				node = (Node) xPath.evaluate(nodeName, nodeStartFrom,
						XPathConstants.NODE);
				if (node == null) {
					if (createIfNotExist) {
						node = document.createElement(nodeName);
						nodeStartFrom.appendChild(node);
					} else {
						return null;
					}
				}
				nodeStartFrom = node;
			} catch (XPathExpressionException e) {
				e.printStackTrace();
			}
		}
		return nodeStartFrom;
	}

	public static void saveDocument(Document document, ByteArrayOutputStream os)
			throws TransformerException {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		Transformer transformer = tFactory.newTransformer();

		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
				"4");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		DOMSource dmSource = new DOMSource(document);
		StreamResult result = new StreamResult(os);

		transformer.transform(dmSource, result);
	}
	
	public static String saveDocumentToString(Document document) throws TransformerException{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		saveDocument(document, os);
		return os.toString();
	}

	public static void removeChildNodes(Node nodeByPath) {
		for(;nodeByPath.getChildNodes().getLength()>0;){
			nodeByPath.removeChild(nodeByPath.getFirstChild());
		}
	}

}
